/*
 * Copyright 2012-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.logging.logback;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import ch.qos.logback.core.util.FileSize;
import ch.qos.logback.core.util.OptionHelper;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.LoggingInitializationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.PropertySourcesPropertyResolver;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.nio.charset.Charset;

/**
 * 在spring boot中对logback的默认配置.没有使用常规的xml文件的方式来实现,而是通过该类进行api的配置,目的是改善启动时间.
 * Default logback configuration used by Spring Boot. Uses {@link LogbackConfigurator} to
 * improve startup time. See also the {@code defaults.xml}, {@code console-appender.xml}
 * and {@code file-appender.xml} files provided for classic {@code logback.xml} use.
 *
 * @author Phillip Webb
 * @since 1.1.2
 */
class DefaultLogbackConfiguration {

	/*
	 * %clr:由ColorConverter 进行处理
	 * %d{yyyy-MM-dd HH:mm:ss.SSS}: 输出时间
	 * ${LOG_LEVEL_PATTERN:-%5p}: 日志级别，并且使用5个字符靠左对齐
	 * ${PID:- }:线程id
	 * %15.15t:t-->线程 %15.15 如果线程名小于15个字符,则在左边填充空格.如果大于15个字符，则进行截断
	 * %-40.40logger{39}: 日志输出者的名字,-40.40 : 如果线程名小于40个字符,则在右边填充空格.如果大于40个字符，则进行截断
	 * %m:日志
	 * %n:换行符
	 * {LOG_EXCEPTION_CONVERSION_WORD:-%wEx}: 由ExtendedWhitespaceThrowableProxyConverter 进行处理
	 */
	
	//console 日志格式
	private static final String CONSOLE_LOG_PATTERN = "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} "
			+ "%clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} "
			+ "%clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} "
			+ "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}";

	//文件的 日志格式,需要配置logging.file或者logging.path 才生效
	private static final String FILE_LOG_PATTERN = "%d{yyyy-MM-dd HH:mm:ss.SSS} "
			+ "${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}";

	private static final Charset UTF8 = Charset.forName("UTF-8");

	private final PropertyResolver patterns;

	private final LogFile logFile;

	DefaultLogbackConfiguration(LoggingInitializationContext initializationContext,
			LogFile logFile) {
		//实例化PropertyResolver
		this.patterns = getPatternsResolver(initializationContext.getEnvironment());
		this.logFile = logFile;
	}

	private PropertyResolver getPatternsResolver(Environment environment) {
		if (environment == null) {
			return new PropertySourcesPropertyResolver(null);
		}
		return RelaxedPropertyResolver.ignoringUnresolvableNestedPlaceholders(environment,
				"logging.pattern.");
	}

	public void apply(LogbackConfigurator config) {
		synchronized (config.getConfigurationLock()) {
			//设置conversionRule,logger
			base(config);
			//实例化consoleAppender
			Appender<ILoggingEvent> consoleAppender = consoleAppender(config);
			//如果logFile 不等于null,
			if (this.logFile != null) {
				//则创建fileAppender,添加到rootLogger中
				/*
					<root level="INFO">
						<appender-ref ref="CONSOLE" />
						<appender-ref ref="FILE" />
					</root>
				*/
				Appender<ILoggingEvent> fileAppender = fileAppender(config,
						this.logFile.toString());
				config.root(Level.INFO, consoleAppender, fileAppender);
			}
			else {
				//只添加consoleAppender到rootLogger中
				/*
					<root level="INFO">
						<appender-ref ref="CONSOLE" />
					</root>
				*/
				config.root(Level.INFO, consoleAppender);
			}
		}
	}

	private void base(LogbackConfigurator config) {
		//相当于在spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml
		config.conversionRule("clr", ColorConverter.class);
		config.conversionRule("wex", WhitespaceThrowableProxyConverter.class);
		config.conversionRule("wEx", ExtendedWhitespaceThrowableProxyConverter.class);
		LevelRemappingAppender debugRemapAppender = new LevelRemappingAppender(
				"org.springframework.boot");
		config.start(debugRemapAppender);
		//相当于在spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml
		config.appender("DEBUG_LEVEL_REMAPPER", debugRemapAppender);
		//相当于在spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml
		config.logger("org.apache.catalina.startup.DigesterFactory", Level.ERROR);
		config.logger("org.apache.catalina.util.LifecycleBase", Level.ERROR);
		config.logger("org.apache.coyote.http11.Http11NioProtocol", Level.WARN);
		config.logger("org.apache.sshd.common.util.SecurityUtils", Level.WARN);
		config.logger("org.apache.tomcat.util.net.NioSelectorPool", Level.WARN);
		config.logger("org.crsh.plugin", Level.WARN);
		config.logger("org.crsh.ssh", Level.WARN);
		config.logger("org.eclipse.jetty.util.component.AbstractLifeCycle", Level.ERROR);
		config.logger("org.hibernate.validator.internal.util.Version", Level.WARN);
		config.logger("org.springframework.boot.actuate.autoconfigure."
				+ "CrshAutoConfiguration", Level.WARN);
		config.logger("org.springframework.boot.actuate.endpoint.jmx", null, false,
				debugRemapAppender);
		config.logger("org.thymeleaf", null, false, debugRemapAppender);
	}
	
	/**
	 * 相当于spring-boot/src/main/resources/org/springframework/boot/logging/logback/console-appender.xml
	 * @param config
	 * @return
	 */
	private Appender<ILoggingEvent> consoleAppender(LogbackConfigurator config) {
		//实例化ConsoleAppender和PatternLayoutEncoder
		ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
		PatternLayoutEncoder encoder = new PatternLayoutEncoder();
		//获取logging.pattern.console的配置,如果获取不到则使用CONSOLE_LOG_PATTERN,然后设置到ConsoleAppender 输出格式中
		String logPattern = this.patterns.getProperty("console", CONSOLE_LOG_PATTERN);
		encoder.setPattern(OptionHelper.substVars(logPattern, config.getContext()));
		encoder.setCharset(UTF8);
		config.start(encoder);
		// 启动ConsoleAppender
		appender.setEncoder(encoder);
		//设置appender的名字为CONSOLE
		config.appender("CONSOLE", appender);
		return appender;
	}

	private Appender<ILoggingEvent> fileAppender(LogbackConfigurator config,
			String logFile) {
		RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<ILoggingEvent>();
		PatternLayoutEncoder encoder = new PatternLayoutEncoder();
		String logPattern = this.patterns.getProperty("file", FILE_LOG_PATTERN);
		encoder.setPattern(OptionHelper.substVars(logPattern, config.getContext()));
		appender.setEncoder(encoder);
		config.start(encoder);
		appender.setFile(logFile);
		setRollingPolicy(appender, config, logFile);
		setMaxFileSize(appender, config);
		config.appender("FILE", appender);
		return appender;
	}

	private void setRollingPolicy(RollingFileAppender<ILoggingEvent> appender,
			LogbackConfigurator config, String logFile) {
		FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
		rollingPolicy.setFileNamePattern(logFile + ".%i");
		appender.setRollingPolicy(rollingPolicy);
		rollingPolicy.setParent(appender);
		config.start(rollingPolicy);
	}

	private void setMaxFileSize(RollingFileAppender<ILoggingEvent> appender,
			LogbackConfigurator config) {
		SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>();
		try {
			triggeringPolicy.setMaxFileSize(FileSize.valueOf("10MB"));
		}
		catch (NoSuchMethodError ex) {
			// Logback < 1.1.8 used String configuration
			Method method = ReflectionUtils.findMethod(SizeBasedTriggeringPolicy.class,
					"setMaxFileSize", String.class);
			ReflectionUtils.invokeMethod(method, triggeringPolicy, "10MB");
		}
		appender.setTriggeringPolicy(triggeringPolicy);
		config.start(triggeringPolicy);
	}

}
